package jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class Sqlplus {
	public static void main(String[] args) {
		Connection con = null;
		Scanner in = new Scanner(System.in);
		try {
			con=DBUtil.open();
			while(true){
				String sql = input(in);
				if("exit".equals(sql))
					break;
				try {
					if(sql.toLowerCase().startsWith("select")){
						query(con,sql);
					}else{
						update(con,sql);
					}
				} catch (Exception e) {
					System.out.println("sql语句执行出错：");
					System.out.println(e.getMessage());
					continue;
				}
			}
		} catch (Exception e) {
			System.out.println("程序出错，退出");
		}finally{
			DBUtil.close(con, null, null);
		}
	}

	private static void update(Connection con, String sql) throws SQLException {
		Statement stm = con.createStatement();
		try{
			int i = stm.executeUpdate(sql);
			if(sql.startsWith("update")){
				if(i>1)
					System.out.println(i+" rows updated");
				else
					System.out.println(i+" row updated");
			}else if(sql.startsWith("delete")){
				if(i>1)
					System.out.println(i+" rows deleted");
				else
					System.out.println(i+" row deleted");
			}else if(sql.startsWith("insert")){
				if(i>1)
					System.out.println(i+" rows inserted");
				else
					System.out.println(i+" row inserted");
			}
		}finally{
			DBUtil.close(null, stm, null);
		}
	}

	private static void query(Connection con, String sql) throws SQLException {
		Statement stm = con.createStatement();
		ResultSet rs = stm.executeQuery(sql);
		ResultSetMetaData m = rs.getMetaData();
		int columns = m.getColumnCount();
		System.out.println(columns);
		//循环显示列名
		for(int i=1;i<=columns;i++){
			System.out.print(m.getColumnName(i));
			System.out.print("\t\t");
		}
		System.out.println();
		//显示数据
		while(rs.next()){
			for(int i = 1;i<=columns;i++){
				System.out.print(rs.getString(i));
				System.out.print("\t\t");
			}
			System.out.println();
		}
		DBUtil.close(null, stm, rs);
	}

	private static String input(Scanner in) {
		String sql = "";
		int i=0;
		System.out.print("SQL>");
		do {
			i++;
			if(i>1){
				System.out.print("    "+i+" ");
			}
			sql+=" "+in.nextLine();
		} while (!sql.trim().endsWith(";"));
		sql = sql.trim();
		sql = sql.substring(0,sql.length()-1);
		return sql;
	}
}
